<template>
  <div class="main">
    <Search :initData="initSearchData" @emitSearchData="getSearchData"></Search>
    <div class="content">
      <a-row :gutter="[8, 8]">
        <Pie :span="8" :pieData="pieData0"></Pie>
        <Pie :span="8" :pieData="pieData1"></Pie>
        <Pie :span="8" :pieData="pieData2"></Pie>
        <Pie :span="8" :pieData="pieData3"></Pie>
        <Pie :span="8" :pieData="pieData4"></Pie>
        <Pie :span="8" :pieData="pieData5"></Pie>
      </a-row>
    </div>
  </div>
</template>

<script>
import Pie from "@/components/echart/pie";
import Search from "@/components/search/statisticsSearch";
import { buildDateAxis } from "@/unit/tool";
import api from "@/server/userConfig";

function buildPieData(object, titleStr) {
  let lists = [{ option: {}, data: [] }];
  let dataLists = [];
  let legendData = [];
  let selected = {};
  let showCount = 10;
  let stateType = [
    "",
    "已报单",
    "已指派",
    "",
    "",
    "待评价",
    "已评价",
    "",
    "进行中",
    "暂  停",
    "内部关闭"
  ];

  let serviceType = ["", "不满意", "一般", "满意", "很满意"];
  for (const key in object) {
    if (titleStr == "订单状态") {
      dataLists.push({
        name: stateType[key],
        value: object[key].number
      });
    } else if (titleStr == "服务满意度") {
      dataLists.push({
        name: serviceType[key],
        value: object[key].number
      });
    } else {
      dataLists.push({
        name: key,
        value: object[key].number
      });
    }

    // if (object.hasOwnProperty(key)) {
    //   if (isNaN(key)) {
    //     dataLists.push({
    //       name: key,
    //       value: object[key].number
    //     });
    //   } else {
    //     dataLists.push({
    //       name: stateType[key],
    //       value: object[key].number
    //     });
    //   }
    // }
  }

  dataLists = dataLists
    .sort((a, b) => {
      return b.value - a.value;
    })
    .slice(0, showCount);

  legendData = dataLists.map((item, index) => {
    let name = item.name == "" ? "未知字段" : item.name;
    selected[name] = index < showCount ? true : false;
    return name;
  });

  lists[0].option = {
    radius: "120",
    center: ["200", "200"],
    label: {
      position: "inner",
      formatter: function(e) {
        let newValue = Math.ceil(parseFloat(e.percent));
        if (newValue >= 5) {
          return newValue + "%";
        } else {
          return "";
        }
        // return Math.ceil(parseFloat(e.percent)) + "%";
      }
    }
  };

  lists[0].data = dataLists;
  return {
    title: {
      text: titleStr,
      left: "44",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "vertical",
      right: "80",
      top: "80",
      icon: "circle",
      data: legendData,
      selected: selected,
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: "#000000"
      },
      formatter: params => {
        let str = "";
        dataLists.forEach((itme, index) => {
          if (params == itme.name) {
            str = `${itme.name} : ${itme.value}`;
          }
          return false;
        });

        return str;
      }
    },
    dataLists: lists
  };
}

// function buildLineLists(object, option) {
//   let { startTime, endTime, timeFormat } = option;
//   let lists = [];
//   let xAxisData = buildDateAxis({ timeFormat, startTime, endTime });

//   for (const key in object) {
//     if (object.hasOwnProperty(key)) {
//       lists.push({
//         option: {
//           name: key
//         },
//         data: transformTimeArray(object[key])
//       });
//     }
//   }
//   return {
//     xAxisData,
//     lists
//   };
// }

export default {
  name: "ServiceStatistics",
  components: {
    Search,
    Pie
  },
  data() {
    return {
      initSearchData: {
        districtValue: "全部",
        timeType: "今年",
        endTime: `${this.$Moment()
          .endOf("year")
          .format("YYYY-MM-DD")} 23:59:59`,
        startTime: `${this.$Moment()
          .startOf("year")
          .format("YYYY-MM-DD")} 00:00:00`
      },
      deviceType: [
        { type: "设备类型", key: "pieData0" },
        { type: "保修状态", key: "pieData1" },
        { type: "订单状态", key: "pieData2" },
        { type: "任务类型", key: "pieData3" },
        { type: "服务满意度", key: "pieData4" },
        { type: "片区统计", key: "pieData5" }
      ],
      // deviceType: ["设备类型"],
      deviceTypePieDataLists: [],
      pieData0: {},
      pieData1: {},
      pieData2: {},
      pieData3: {},
      pieData4: {},
      pieData5: {}
    };
  },
  methods: {
    async getFailureStatisticsPieChart(parames, key) {
      const res = await api.failureStatisticsPieChart({
        ownDistrict: parames.ownDistrict,
        startTime: parames.startTime,
        endTime: parames.endTime,
        statisticsType: parames.statisticsType
      });
      console.log(res);

      if (res.MsgCode !== 0) {
        this.$message.warning(`${parames.statisticsType}暂无数据`);
        return;
      }

      this[key] = buildPieData(res.Data, parames.statisticsType);
    },

    getData(parames) {
      this.deviceType.forEach((item, index) => {
        this.getFailureStatisticsPieChart(
          {
            ownDistrict: parames.districtValue,
            startTime: parames.startTime,
            endTime: parames.endTime,
            statisticsType: item.type
          },
          item.key
        );
      });
    },

    getSearchData(value) {
      this.getData(value);
    },

    getLocalStorageData() {
      const phone = localStorage.getItem("phone");
      this.userName = phone;
      if (!phone) {
        this.$router.push("/");
      }
    },
    callback(key) {}
  },

  created() {
    this.getLocalStorageData();
  },

  mounted() {
    console.log(this.initSearchData);
    this.getData(this.initSearchData);
  }
};
</script>

<style scoped="scoped">
.main {
  height: 100%;
  width: 100%;
  padding: 0px 0px 0px 0px;
}

.main > .content {
  padding: 16px;
  background: #ecf2f7;
}
</style>
